<?php
/**
 * 大赛评委
 */
namespace Beerus\Modules\DesignerCompetition2022\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DesignerCompetition2021\audit\DcAuditFirstResult;
use Doraemon\model\Member;
use Doraemon\model\DesignerCompetition2021\audit\admin\DcAuditFirstWorkAdmin;
use Doraemon\model\DesignerCompetition2021\audit\DcAuditReviewer;
use Doraemon\model\ReDesignerCompetition\Audit\DcAuditReviewerHelper;
use Doraemon\pockets\constInterface\Designer\DesignerCompetition2022;
use Doraemon\service\DesignerCompetition\Audit\Audit2022\AuditTrait;
use Doraemon\service\DesignerCompetition\DcCommon;
use Doraemon\service\DesignerCompetition2021\Audit;
use Doraemon\service\DesignerCompetition2021\DcAdmin;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;

class ReviewerController extends Controller implements DesignerCompetition2022 {
    const PAGE_SIZE = 10;
    use AuditTrait;

    public function index(Request $request, Content $content) {
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $request = $request->all();
        $condition = [];
        if (!empty($request['reviewer_uid'])) {
            $condition['reviewer_uid'] = $request['reviewer_uid'];
        }
        if (!empty($request['audit_step'])) {
            $condition['audit_step'] = $request['audit_step'];
        }
        $total = (DcAuditReviewerHelper::getInstance(self::SIGN_YEAR))->getReviewerCntByCondition($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize,
        ];
        $list = (DcAuditReviewerHelper::getInstance(self::SIGN_YEAR))->getReviewerListByCondition($condition);
        $this->formatList($list);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(4, function ($filter) {
                        $filter->equal('reviewer_uid', '评审员UID')->placeholder('请输入uid');
                    });
                    $filter->column(4, function ($filter) {
                        $filter->equal('audit_step', '评审阶段')->select(DcAdmin::AUDIT_STEP_TXT);
                    });
                    $filter->expand();
                });

                $grid->column('id', 'ID');
                $grid->column('reviewer_uid', '评审员UID');
                $grid->column('reviewer_nick', '评审员昵称');
                $grid->column('audit_step', '评审阶段')->display(function() {
                    return DcAdmin::AUDIT_STEP_TXT[$this->audit_step];
                });
                $grid->column('award_ids', '评选奖项')->display(function() {
                    return $this->award_list ? implode('<br>', $this->award_list) : '';
                });
                $grid->column('audit_status_list', '评选进度')->width(300)->display(function () {
                    return $this->audit_status_list ? implode('<br>', $this->audit_status_list) : '';
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            }
        );
        return $content
            ->header('大赛评审列表')
            ->row($gridList);
    }

    public function edit(Request $request, Content $content, $id = 0) {
        $data = (DcAuditReviewerHelper::getInstance(self::SIGN_YEAR))->getReviewerItemById($id);
        $form = new Form($data);
        if (!empty($id)) {
            $form->text('id', 'ID')->readOnly();
        }
        $form->text('reviewer_uid', '评审员UID')->required();
        $form->select('audit_step', '评审阶段')
            ->options(self::AUDIT_STEP_TXT)
            ->default(self::AUDIT_STEP_FIRST)
            ->required();

        $aAwardList = (new DcCommon())->getAllAwardListWithTypeGroup()['award_list_with_id_key'];
        $aAwardListWithName = array_column($aAwardList, 'award_name', 'id');
        $form->multipleSelect('award_ids', '要评审的奖项')->options($aAwardListWithName)->required();
        $form->confirm('确定提交吗？');
        $form->action('/admin/DesignerCompetition2022/reviewer/save');

        $header = '信息修改';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => '评审员列表'],
                ['text' => '编辑评审员信息'],
            )->row($tab);
    }

    public function save(Request $request) {
        $reviewerUid = $request->input('reviewer_uid');
        $aAwardIds = $request->input('award_ids');
        $auditStep = $request->input('audit_step');
        // 评审员uid是否存在判断
        if (!Member::getUserInfo($reviewerUid)) {
            $error = new MessageBag(['title' => '该评审员不存在']);
            return back()->with(compact('error'));
        }
        if (!in_array($auditStep, self::AUDIT_STEP_INDEX)) {
            $error = new MessageBag(['title' => '该评审阶段不存在']);
            return back()->with(compact('error'));
        }
        if ((DcAuditReviewerHelper::getInstance(self::SIGN_YEAR))->getReviewerItemByUid($reviewerUid, $auditStep)) {
            $error = new MessageBag(['title' => '该评审已存在']);
            return back()->with(compact('error'));
        }
        $aAwardIds = array_filter($aAwardIds);
        $sAwardIds = implode(',', $aAwardIds);
        if (false === (DcAuditReviewerHelper::getInstance(self::SIGN_YEAR))->createReviewer($reviewerUid, $sAwardIds, $auditStep)) {
            $error = new MessageBag(['title' => '新增评审失败']);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => '操作成功']);
        return redirect('/admin/DesignerCompetition2022/reviewer')->with(compact('success'));
    }

    // 删除奖项
    public function del($id) {
        $reviewer = (DcAuditReviewerHelper::getInstance(self::SIGN_YEAR))->getReviewerItemById($id);
        if ($reviewer) {
            if ((DcAuditReviewerHelper::getInstance(self::SIGN_YEAR))->removeReviewerById($id) === false) {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "该评审不存在",
            ]);
        }
    }

    public function formatList(&$list) {
        $aAwardGroup = (new DcCommon(self::SIGN_YEAR))->getAllAwardListWithTypeGroup();
        foreach ($list as &$item) {
            $item['reviewer_nick'] = Member::getNickByUid($item['reviewer_uid']) ?? '';
            $item['award_list'] = $item['audit_status_list'] = [];
            if ($item['award_ids']) {
                $aAwardIds = explode(',', $item['award_ids']);
                foreach ($aAwardIds as $iAwardId) {
                    $item['award_list'][] = $aAwardGroup['award_list_with_id_key'][$iAwardId]['award_name'];
                    $sAuditStatusName = self::getAuditStatusName($iAwardId);
                    $item['audit_status_list'][] = $aAwardGroup['award_list_with_id_key'][$iAwardId]['award_name'] . ':' . self::FINISH_AUDIT_TXT[$item[$sAuditStatusName]];
                }
            }
        }
    }
}
